﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.PM0.Controllers;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.DAO.Admin;
using DHQGHN.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;
namespace DHQGHN.PM0.Controllers.Admin
{
    public class EducationTrainingController : BaseController
    {
        EducationTrainingBO educationTrainingBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(EducationTrainingController));
        public ActionResult Index(EducationTrainingModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (a == null) a = new EducationTrainingModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                var model = search(a, pageIndex, currentId, false);
                return View("~/Views/EducationTraining/EducationTraining.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        //Hiện thị form thêm mới, sửa xóa
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateEducationTraining(string id)
        {
            try
            {
                EducationTrainingModel model = null;
                if (!String.IsNullOrEmpty(id))
                {
                    educationTrainingBO = new EducationTrainingBO();
                    model = new EducationTrainingModel(educationTrainingBO.GetEducationTraniningById(id));
                }
                if (model == null)
                {
                    model = new EducationTrainingModel()
                    {
                        EDUCATION_TRAINING_ID = "",
                        Name = "",
                        Code = "",
                        Descriptions = ""
                    };
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/EducationTraining/_EducationTrainingModel.cshtml", model);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        //search
        private DataPage<EducationTrainingModel> search(EducationTrainingModel aModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                educationTrainingBO = new EducationTrainingBO();

                var DALModel = educationTrainingBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<EducationTrainingModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.EducationTrainingModel educationTraining in lstItem)
                {
                    models.Data.Add(new EducationTrainingModel(educationTraining));
                }

                EducationTrainingModel model = null;
                if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => Equals(user.EDUCATION_TRAINING_ID, currentId));
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = aModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "EducationTraining",
                        CurrentPage = pageIndex,
                        InputSearchId = "",
                        TagetReLoadId = "educationtraining-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        //actionSearch
        [HttpPost]
        public ActionResult actionSearch(EducationTrainingModel aModel = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = "")
        {
            try
            {
                if (aModel == null) aModel = new EducationTrainingModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/EducationTraining/_EducationTrainingList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //action thêm mới sửa xóa
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateEducationTraining(EducationTrainingModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    educationTrainingBO = new EducationTrainingBO();
                    bool result = educationTrainingBO.createOrUpdateEducationTraining(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<EducationTrainingModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateEducationTraining", model);

                        if (!(String.IsNullOrEmpty(model.EDUCATION_TRAINING_ID) && String.IsNullOrWhiteSpace(model.EDUCATION_TRAINING_ID)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật trình độ đào tạo thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới trình độ đào tạo thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }
        //action delete
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    educationTrainingBO = new EducationTrainingBO();
                    bool result = educationTrainingBO.deleteEducationTraining(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(id),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa trình độ đào tạo thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }
        //Kiểm tra tên đào tạo học vấn đã tồn tại chưa
        public JsonResult CheckExistEducationTrainingName(string name, string EDUCATION_TRAINING_ID)
        {
            try
            {
                EducationTrainingModel educationTrainingModel = new EducationTrainingModel()
                {
                    Name = name

                };
                var model = search(educationTrainingModel, 0, "", true);
                var isExist = false;
                if (model.Data.Any())
                {
                    var lstItem = model.Data;
                    foreach (EducationTrainingModel educationTraining in lstItem)
                    {
                        if (!(String.IsNullOrEmpty(EDUCATION_TRAINING_ID) && String.IsNullOrWhiteSpace(EDUCATION_TRAINING_ID)))
                        {
                            if (!Equals(educationTraining.EDUCATION_TRAINING_ID, EDUCATION_TRAINING_ID))
                            {
                                isExist = true;
                                break;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.EducationTrainingNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        //
        public JsonResult CheckExistEducationTrainingCode(string code, string EDUCATION_TRAINING_ID)
        {
            try
            {
                EducationTrainingModel educationTrainingModel = new EducationTrainingModel()
                {
                    Code = code
                };
                var model = search(educationTrainingModel, 0, "", true);
                var isExist = false;
                if (model.Data.Any())
                {


                    var lstItem = model.Data;
                    foreach (EducationTrainingModel educationTraining in lstItem)
                    {
                        if (!(String.IsNullOrEmpty(EDUCATION_TRAINING_ID) || String.IsNullOrWhiteSpace(EDUCATION_TRAINING_ID)))
                        {
                            if (!Equals(educationTraining.EDUCATION_TRAINING_ID, EDUCATION_TRAINING_ID))
                            {
                                isExist = true;
                                break;
                            }
                        }
                        else
                        {
                            //Kiem tra truong hop them moi
                            isExist = true;
                            break;
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.EducationTrainingCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "EducationTraningController";
        }
    }
}